package com.abocode.aichat.server.context.endpoint;

import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.context.handler.ProtocolServerInboundHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

/**
 * @author guanxf
 */
public class ProtocolChannelHandlerRegister extends ChannelInitializer {
    private static final int ALL_IDLE_TIME_OUT = 0;
    private static final int READ_IDLE_TIME_OUT = 900;
    private static final int WRITE_IDLE_TIME_OUT = 0;
    private ServerRuntimeContext serverRuntimeContext;

    public ProtocolChannelHandlerRegister(ServerRuntimeContext serverRuntimeContext) {
        this.serverRuntimeContext = serverRuntimeContext;
    }
    @Override
    protected void initChannel(Channel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast("timeout", new IdleStateHandler(READ_IDLE_TIME_OUT, WRITE_IDLE_TIME_OUT, ALL_IDLE_TIME_OUT));
        pipeline.addLast("handler", new ProtocolServerInboundHandler(serverRuntimeContext));
    }
}
